import { View, Text, Button } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { getCurrentEnv } from '../../utils/payment';
import './index.scss';

// 订单接口
interface Order {
  id: number;
  orderNo: string;
  customerName: string;
  customerPhone: string;
  totalAmount: number;
  status: string;
  paymentMethod: string;
  createTime: string;
  products: Array<{
    name: string;
    quantity: number;
    price: number;
  }>;
}

export default function OrderDetail() {
  const router = useRouter();
  const { orderId } = router.params;
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (orderId) {
      loadOrderDetail();
    }
  }, [orderId]);

  const loadOrderDetail = async () => {
    try {
      setLoading(true);
      
      if (getCurrentEnv() === 'development') {
        // 开发环境：使用模拟数据
        const mockOrder: Order = {
          id: Number(orderId) || 1,
          orderNo: `ORD${Date.now()}`,
          customerName: '测试用户',
          customerPhone: '13800138000',
          totalAmount: 1680,
          status: 'paid',
          paymentMethod: '微信支付',
          createTime: new Date().toLocaleString('zh-CN'),
          products: [
            {
              name: '寿衣',
              quantity: 1,
              price: 1680
            }
          ]
        };
        setOrder(mockOrder);
        console.log('🎯 [开发环境] 使用模拟订单数据:', mockOrder);
      } else {
        // 生产环境：调用真实API
        const { getOrderById } = await import('../../api/order');
        const response = await getOrderById(Number(orderId));
        if (response.isSuccess) {
          setOrder(response.data);
        }
      }
    } catch (error) {
      console.error('获取订单详情失败:', error);
      Taro.showToast({
        title: '获取订单详情失败',
        icon: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleBackHome = () => {
    Taro.switchTab({
      url: '/pages/index/index'
    });
  };

  if (loading) {
    return (
      <View className='order-detail-container'>
        <View className='loading'>加载中...</View>
      </View>
    );
  }

  if (!order) {
    return (
      <View className='order-detail-container'>
        <View className='error'>订单不存在</View>
      </View>
    );
  }

  return (
    <View className='order-detail-container'>
      {/* 支付成功提示 */}
      <View className='success-tip'>
        <View className='success-icon'>✓</View>
        <Text className='success-text'>支付成功</Text>
        <Text className='success-desc'>您的订单已提交，我们会尽快为您处理</Text>
      </View>

      {/* 订单信息 */}
      <View className='order-info'>
        <View className='info-row'>
          <Text className='label'>订单号：</Text>
          <Text className='value'>{order.orderNo}</Text>
        </View>
        <View className='info-row'>
          <Text className='label'>下单时间：</Text>
          <Text className='value'>{order.createTime}</Text>
        </View>
        <View className='info-row'>
          <Text className='label'>支付方式：</Text>
          <Text className='value'>{order.paymentMethod}</Text>
        </View>
        <View className='info-row'>
          <Text className='label'>订单状态：</Text>
          <Text className='value status'>{getStatusText(order.status)}</Text>
        </View>
      </View>

      {/* 客户信息 */}
      <View className='customer-info'>
        <View className='section-title'>客户信息</View>
        <View className='info-row'>
          <Text className='label'>姓名：</Text>
          <Text className='value'>{order.customerName}</Text>
        </View>
        <View className='info-row'>
          <Text className='label'>电话：</Text>
          <Text className='value'>{order.customerPhone}</Text>
        </View>
      </View>

      {/* 商品信息 */}
      <View className='product-info'>
        <View className='section-title'>商品信息</View>
        {order.products.map((product, index) => (
          <View key={index} className='product-item'>
            <View className='product-name'>{product.name}</View>
            <View className='product-details'>
              <Text className='quantity'>数量：{product.quantity}</Text>
              <Text className='price'>¥{product.price}</Text>
            </View>
          </View>
        ))}
        <View className='total-amount'>
          <Text className='total-label'>订单总额：</Text>
          <Text className='total-value'>¥{order.totalAmount}</Text>
        </View>
      </View>

      {/* 底部按钮 */}
      <View className='bottom-actions'>
        <Button className='back-btn' onClick={handleBackHome}>
          返回首页
        </Button>
      </View>
    </View>
  );
}

function getStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
}
